package com.sugon.modules.mold.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.sugon.dao.ModuleReplacePartDao;
import com.sugon.entity.*;
import com.sugon.modules.base.consts.SysApproveStatusConst;
import com.sugon.modules.base.model.dto.HandleApproveResult;
import com.sugon.modules.base.service.impl.AbstractErmsBaseApproveManager;
import com.sugon.modules.mold.consts.MoldReplacePartProgress;
import com.sugon.modules.mold.consts.MoldSpStockState;
import com.sugon.modules.mold.model.vo.ModuleReplacePartParam;
import com.sugon.modules.mold.service.IMoldReplacePartManager;
import com.sugon.modules.sys.consts.ProcessProgressStatus;
import com.sugon.service.*;
import com.sugon.utils.PageUtils;
import com.sugon.utils.ProcessInfoEnum;
import com.sugon.utils.Query;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author ： YuXD
 * @description： 模具更换配件Manager实现类
 * @date ： 2020-11-12 上午 7:41
 * @version: 1.0
 */
@Slf4j
@Service
public class MoldReplacePartManagerImpl extends AbstractErmsBaseApproveManager implements IMoldReplacePartManager {

    @Autowired
    private ModuleReplacePartService moduleReplacePartService;
    @Autowired
    private ModulPositionCorrelationService moldPositionService;
    @Autowired
    private ModuleTimesSynNoticeService moduleTimesSynNoticeService;
    @Autowired
    private ModuleArchivesService moduleArchivesService;
    @Autowired
    private ModuleReplacePartDao moduleReplacePartDao;
    @Resource
    private SysProcessInfoService processInfoService;
    @Resource
    private SysMsgService msgService;
    @Resource
    private ModuleSpStockService moduleSpStockService;
    @Resource
    private ModuleSpDeptStockService moduleSpDeptStockService;
    @Resource
    private ModuleSpPurchasingBatchService moduleSpPurchasingBatchService;

    /**
     * queryList
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryList(Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<ModuleReplacePartEntity> moduleReplacePartList = moduleReplacePartService.queryList(query);
        int total = moduleReplacePartService.queryTotal(query);
        return new PageUtils(moduleReplacePartList, total, query.getLimit(), query.getPage());
    }

    /**
     * addMoldReplacePartRecord
     *
     * @param moduleReplacePartParam
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addMoldReplacePartRecord(ModuleReplacePartParam moduleReplacePartParam) {
        ModuleReplacePartEntity moduleReplacePart = new ModuleReplacePartEntity();
        CopyOptions copyOptions = CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true);
        BeanUtil.copyProperties(moduleReplacePartParam, moduleReplacePart, copyOptions);
        moduleReplacePart.setReplaceDate(DateUtil.date());
        List<String> moldPositionList = moduleReplacePartParam.getMoldPositionList();
        for (String moldPositionId : moldPositionList) {
            ModulPositionCorrelationEntity moldPosition = moldPositionService.queryObject(moldPositionId);
            Assert.notNull(moldPosition, "模具关联位置[{}]不存在，请确认！", moldPosition);
            // 校验当前模具位置，是否重复选择，如果已选择，则不做任何处理
            List<ModuleReplacePartEntity> existedReplaceParts = moduleReplacePartDao.query(moduleReplacePartParam.getTypeMethod(), moduleReplacePartParam.getReplaceCode(), moldPositionId);
            if (CollectionUtil.isNotEmpty(existedReplaceParts)) {
                continue;
            }
            moduleReplacePart.setModulePositionId(moldPosition.getId());
            moduleReplacePart.setFittingName(moldPosition.getPositionName());
            moduleReplacePart.setLifeStandard(moldPosition.getLifeStandard());
            moduleReplacePart.setRealUseTime(moldPosition.getCurrentTime());
            moduleReplacePart.setType(moldPosition.getModType());
            addReplacePartCommonHandle(moduleReplacePart);
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteMoldReplacePartRecord(ModuleReplacePartEntity moduleReplacePart) {
        Assert.isTrue(moduleReplacePartService.delete(moduleReplacePart.getId()) > 0);
        // 1、恢复模具关联位置模次同步功能
        ModulPositionCorrelationEntity moldPositionCorrelation = new ModulPositionCorrelationEntity();
        moldPositionCorrelation.setId(moduleReplacePart.getModulePositionId());
        moldPositionCorrelation.setIsNewSyn(1);
        moldPositionCorrelation.setPosStatus(1);
        moldPositionService.update(moldPositionCorrelation);

        // 2、校验是否关联型芯，如果已关联，那么需要更新状态
        String stockId = moduleReplacePart.getStockId();
        if (StrUtil.isNotEmpty(stockId)) {
            ModuleSpStockEntity moduleSpStock = moduleSpStockService.queryObject(stockId);
            if (moduleSpStock != null) {
                // 更新库存状态和备件采购批次数
                moduleSpStock.setState(MoldSpStockState.ED);
                moduleSpStock.setStockOutDate(DateUtil.date());
                if (moduleSpStockService.update(moduleSpStock) > 0) {
                    // 实时更新采购批次中的出库数
                    moduleSpDeptStockService.realtimeUpdateDeptStock(moduleSpStock.getWorkshop(), moduleSpStock.getMoldSpId());
                    // 实时更新采购批次中的出库数
                    moduleSpPurchasingBatchService.realtimePurchasingBacthStockState();
                }
            }
        }

        // 3、删除换件流程记录
        processInfoService.delete(ProcessInfoEnum.MDE_BJGH, moduleReplacePart.getId());
        // 4、删除所有通知消息
        msgService.delSysMsgService(moduleReplacePart.getId(), ProcessInfoEnum.MDE_BJGH.name(), null);
        return true;
    }

    /**
     * addMoldReplacePartRecord
     *
     * @param moduleReplacePart
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addMoldReplacePartRecord(ModuleReplacePartEntity moduleReplacePart) {
        return addReplacePartCommonHandle(moduleReplacePart);
    }

    /**
     * handleWorkshopApprove
     *
     * @param approveItemId 审批事项ID
     * @param approveStatus 审批状态
     * @param remark        审批备注
     * @return
     */
    @Override
    public HandleApproveResult handleWorkshopApprove(String approveItemId, Integer approveStatus, String remark) {
        HandleApproveResult handleApproveResult = new HandleApproveResult();
        ModuleReplacePartEntity moduleReplacePart = moduleReplacePartService.queryObject(approveItemId);
        Assert.notNull(moduleReplacePart, "模具换装信息不存在，请确认！");
        // 校验规程进度
        Assert.isTrue(MoldReplacePartProgress.DEPT_APPROVING.equals(moduleReplacePart.getProgress()), "只可以审核处于审核中的模具换件记录！");
        handleApproveResult.setTitle(moduleReplacePart.getMoldId() + "换件" + moduleReplacePart.getFittingName());
        // 如果审核通过
        if (approveStatus == SysApproveStatusConst.PASSED) {
            moduleReplacePart.setProgress(MoldReplacePartProgress.PASSED);
            int rows = moduleReplacePartService.update(moduleReplacePart);
            if (rows > 0) {
                handleApproveResult.setProcessProgressStatus(ProcessProgressStatus.END);
                // 进行模具关联位置换件
                doMoldCorrelatedPositionReplacePart(moduleReplacePart);
            }
        } else if (approveStatus == SysApproveStatusConst.NOT_PASSED) {
            moduleReplacePart.setProgress(MoldReplacePartProgress.NOT_PASSED);
            int rows = moduleReplacePartService.update(moduleReplacePart);
            if (rows > 0) {
                handleApproveResult.setProcessProgressStatus(ProcessProgressStatus.ING);
                handleApproveResult.setUserId(moduleReplacePart.getUpdateUser());
            }
        }
        return handleApproveResult;
    }

    /**
     * 进行模具关联位置换件逻辑
     * 1、套数累加
     * 2、重置寿命,主要是当前次数和剩余寿命
     * 3、通知可以同步模次信息
     *
     * @param moduleReplacePart 模具换件记录
     */
    private synchronized void doMoldCorrelatedPositionReplacePart(ModuleReplacePartEntity moduleReplacePart) {
        ModulPositionCorrelationEntity modulPositionCorrelation = moldPositionService.queryObject(moduleReplacePart.getModulePositionId());
        Assert.notNull(modulPositionCorrelation, "模具关联位置不存在,ID:" + moduleReplacePart.getModulePositionId());
        // 记录上次换件时间,如果没换过，那么就以创建时间为第一次
        Date lastChangeTime = modulPositionCorrelation.getChangeTime();
        if (lastChangeTime == null) {
            lastChangeTime = modulPositionCorrelation.getCreateTime();
        }
        modulPositionCorrelation.setChangeTime(moduleReplacePart.getReplaceDate());
        modulPositionCorrelation.setSetNum(modulPositionCorrelation.getSetNum() + 1);
        modulPositionCorrelation.setResidualLife(modulPositionCorrelation.getLifeStandard());
        modulPositionCorrelation.setPosStatus(3);
        // 换件后这个模具位置的使用次数
        modulPositionCorrelation.setCurrentTime(0);
        moldPositionService.update(modulPositionCorrelation);
        // 生成模次同步通知
        ModuleArchivesEntity moduleArchives = moduleArchivesService.queryObject(moduleReplacePart.getMoldId());
        if (moduleArchives != null) {
            String lastCode = moduleArchives.getLastCode();
            if (StrUtil.isNotEmpty(lastCode)) {
                ModuleTimesSynNoticeEntity moduleTimesSynNotice = new ModuleTimesSynNoticeEntity();
                moduleTimesSynNotice.setMoldNo(lastCode);
                moduleTimesSynNotice.setMoldTypeCode(moduleArchives.getModuleTypeCode());
                moduleTimesSynNotice.setCorrelationPositionId(moduleReplacePart.getModulePositionId());
                moduleTimesSynNotice.setReplaceDate(moduleReplacePart.getReplaceDate());
                moduleTimesSynNotice.setLastReplaceDate(lastChangeTime);
                moduleTimesSynNotice.setApproveDate(moduleReplacePart.getUpdateTime());
                moduleTimesSynNotice.setAddRecordDate(moduleReplacePart.getCreateTime());
                moduleTimesSynNotice.setReplaceRecordId(moduleReplacePart.getId());
                moduleTimesSynNoticeService.save(moduleTimesSynNotice);
            }
        }
    }

    /**
     * 添加换件记录共同处理
     *
     * @param moduleReplacePart
     * @return
     */
    private boolean addReplacePartCommonHandle(ModuleReplacePartEntity moduleReplacePart) {
        boolean result = moduleReplacePartService.save(moduleReplacePart) > 0;
        if (result) {
            // 1、关闭模具关联位置模次同步功能
            ModulPositionCorrelationEntity moldPositionCorrelation = new ModulPositionCorrelationEntity();
            moldPositionCorrelation.setId(moduleReplacePart.getModulePositionId());
            moldPositionCorrelation.setIsNewSyn(0);
            moldPositionCorrelation.setPosStatus(2);
            moldPositionService.update(moldPositionCorrelation);
        }
        return result;
    }

}
